using System.Web;
using Headspring.Training.Core.Model;
using Headspring.Training.Core.Services;

namespace Headspring.Training.Infrastructure.Impl
{
	public class StateCommandVisitor : IStateCommandVisitor
	{
		private readonly IWorkOrderRepository _repository;
		private readonly IUserSession _session;


		public StateCommandVisitor()
		{
		}

		public StateCommandVisitor(IWorkOrderRepository repository,
		                           IUserSession session)
		{
			_repository = repository;
			_session = session;
		}

		public void SaveWorkOrder(WorkOrder workOrder)
		{
			_repository.Save(workOrder);
		}

		public void EditWorkOrder(WorkOrder workOrder)
		{
			redirect("~/workorder/edit?workordernumber=" + workOrder.Number);
		}

		public void GoToWorkOrderSearch(Employee creator, Employee assignee,
		                                WorkOrderStatus status)
		{
			string url =
				string.Format("~/search/list?creator={0}&assignee={1}&status={2}",
				              getNullSafeUserName(creator), getNullSafeUserName(assignee),
				              getNullSafeStatusKey(status));
			HttpResponse response = HttpContext.Current.Response;
			response.Redirect(url);
		}

		public void SendMessage(string message)
		{
			_session.PushUserMessage(new FlashMessage(
			                         	FlashMessage.MessageType.Message, message));
		}

		public void SendError(string message)
		{
			_session.PushUserMessage(new FlashMessage(FlashMessage.MessageType.Error,
			                                          message));
		}

		public void GoToDashboard()
		{
			HttpContext.Current.Response.Redirect("~/");
		}

		protected virtual void redirect(string url)
		{
			HttpResponse response = HttpContext.Current.Response;
			response.Redirect(url);
		}

		private static string getNullSafeStatusKey(WorkOrderStatus status)
		{
			if (status == null)
			{
				return null;
			}

			return status.Key;
		}

		private static string getNullSafeUserName(Employee employee)
		{
			if (employee == null)
			{
				return null;
			}

			return employee.UserName;
		}
	}
}